﻿
Imports std

Public MustInherit Class jobConsumer(Of T As ijob)
    Inherits consumer

    Protected MustOverride Overloads Function workOn(ByVal j As T,
                                                     Optional ByRef ec As eventComb = Nothing) As Boolean

    Protected NotOverridable Overrides Sub workOn(ByVal job As indexedJob)
        assert(Not job Is Nothing AndAlso Not job.job() Is Nothing)
        Dim updater As void(Of indexedJob) = Nothing
        Dim ec As eventComb = Nothing
        If istype(Of T)(job.job()) AndAlso
           workOn(convertor.cast(Of T)(job.job()), ec) Then
            updater = Sub(ByRef j As indexedJob)
                          j.finish()
                      End Sub
            If ec Is Nothing Then
                assert(update(job, updater))
            Else
                assert_begin(New eventComb(Function() As Boolean
                                               Return waitfor(ec) AndAlso
                                                      goto_next()
                                           End Function,
                                           Function() As Boolean
                                               Return ((ec.end_result() AndAlso update(job, updater)) OrElse
                                                       update(job)) AndAlso
                                                      goto_end()
                                           End Function))
            End If
        Else
            assert(update(job))
        End If
    End Sub

    Private Shadows Function update(ByVal job As indexedJob,
                                    Optional ByVal updater As void(Of indexedJob) = Nothing) As Boolean
        assert(Not job Is Nothing AndAlso Not job.job() Is Nothing)
        job.job().respond_lop()
        Return MyBase.update(job, updater)
    End Function
End Class
